﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.UI;
using System.Web.UI.WebControls;
using AutoFix.Base;
using Common;
using BusinessLogicLayer.Manager;
using Objects;
using System.Text;
using System.Web.UI.HtmlControls;

namespace AutoFix
{
    public partial class repair_detail : BasePage
    {
        #region [Private Members]
        /// <summary>
        /// The logged in user
        /// </summary>
        private User applicationUser = null;
        #endregion

        #region [Public Properties]
        /// <summary>
        /// Counter used for step name text
        /// </summary>
        public int Counter { get; set; }
        #endregion

        #region [Base Implementations]
        /// <summary>
        /// Gets or sets a value indicating whether [is login page].
        /// </summary>
        /// <value>
        ///   <c>true</c> if [is login page]; otherwise, <c>false</c>.
        /// </value>
        protected override bool IsLoginPage
        {
            get { return false; }
        }
        /// <summary>
        /// Gets or sets a value indicating whether [is anonymous page].
        /// </summary>
        /// <value>
        ///   <c>true</c> if [is anonymous page]; otherwise, <c>false</c>.
        /// </value>
        protected override bool IsAnonymousPage
        {
            get { return true; }
        }
        /// <summary>
        /// Page name
        /// </summary>
        protected override string PageName
        {
            get { return "Article Detail"; }
        }
        /// <summary>
        /// Gets the authorized user types.
        /// </summary>
        protected override List<UserType> AuthorizedUserTypes
        {
            get { return new List<UserType>(new UserType[] { UserType.Admin, UserType.Contributor, UserType.Guest }); }
        }
        #endregion

        #region [Event Handlers]
        /// <summary>
        /// Handles the Load event of the Page control.
        /// </summary>
        /// <param name="sender">The source of the event.</param>
        /// <param name="e">The <see cref="EventArgs"/> instance containing the event data.</param>
        protected void Page_Load(object sender, EventArgs e)
        {
            applicationUser = this.PageSession.ApplicationUser;
            if (!(Page.IsPostBack))
            {
                LoadPage();
            }
        }

       
        /// <summary>
        /// Handles the change event of the rating button.
        /// </summary>
        /// <param name="sender">The source of the event.</param>
        /// <param name="e">The <see cref="EventArgs"/> instance containing the event data.</param>
        protected void articleRating_Changed(object sender, AjaxControlToolkit.RatingEventArgs e)
        {
            string[] ratingInfo = ((AjaxControlToolkit.Rating)sender).BehaviorID.Split(',');

            string currentRatedValue = e.Value;
            RatingManager ratingManager = new RatingManager();
            ArticleRating articleRating = new ArticleRating();
            try
            {
                articleRating.ArticleID = Convert.ToInt32(ratingInfo[0]);
                articleRating.UserID = Convert.ToInt32(ratingInfo[1]);
                articleRating.Rating = Convert.ToInt32(currentRatedValue);
                articleRating.IsActive = true;
                bool success = ratingManager.UpdateRating(articleRating);
                if (success)
                {
                    this.pageActionMessage.InnerText = "The article was successfully rated.";
                    this.pageActionMessage.Attributes.Add("class", "success-msg");
                }
                else
                {
                    this.pageActionMessage.InnerText = "Failed to rate the following article";
                    this.pageActionMessage.Attributes.Add("class", "error-msg");
                }
            }
            catch (Exception)
            {
                this.pageActionMessage.InnerText = "Unable to rate the following article";
                this.pageActionMessage.Attributes.Add("class", "error-msg");
            }
            finally
            {
                ratingManager = null;
                articleRating = null;
            }

        }
        /// <summary>
        /// binds the step data in the list view
        /// </summary>
        /// <param name="sender">The source of the event.</param>
        /// <param name="e">The <see cref="EventArgs"/> instance containing the event data.</param>
        protected void lstSteps_ItemDataBound(object sender, ListViewItemEventArgs e)
        {
            Counter = Counter + 1;
            Label lblStepTitle = (Label)e.Item.FindControl("lblStepTitle");
            GetStepsUserOrArticle step = (GetStepsUserOrArticle)e.Item.DataItem;
            lblStepTitle.Text = String.Format("Step {0}: {1}", Counter, step.StepName);
            bool isVideo = step.StepURL.Contains(".mp4");
            int articleID = Convert.ToInt32(Request.QueryString["article"]);

            if (isVideo)
            {
                Panel itemHolder = (Panel)e.Item.FindControl("itemHolder");
                itemHolder.Visible = true;
                HtmlControl vdoStep = (HtmlControl)itemHolder.FindControl("vdoStep");
                StringBuilder pathToFile = new StringBuilder();
                pathToFile.Append(AppConfiguration.ArticlePath);
                pathToFile.Append("/");
                pathToFile.Append(articleID);
                pathToFile.Append("/");
                pathToFile.Append(step.StepURL);
                string completePath = pathToFile.ToString();
                HtmlGenericControl videoSource = new HtmlGenericControl();
                videoSource.TagName = "source";
                videoSource.Attributes.Add("src", completePath);
                videoSource.Attributes.Add("type", "video/mp4");
                vdoStep.Controls.Add(videoSource);
                pathToFile = null;

            }
            else
            {
                Label lblStepContent = (Label)e.Item.FindControl("lblStepContent");
                StringBuilder pathToFile = new StringBuilder();
                pathToFile.Append(AppConfiguration.ArticlePath);
                pathToFile.Append("/");
                pathToFile.Append(articleID);
                pathToFile.Append("/");
                pathToFile.Append(step.StepURL);
                string completePath = Server.MapPath(pathToFile.ToString());
                lblStepContent.Visible = true;
                lblStepContent.Text = LoadStepData(completePath);
                pathToFile = null;
            }
        }
        /// <summary>
        /// Handles the click event of the add comment button
        /// </summary>
        /// <param name="sender">The source of the event.</param>
        /// <param name="e">The <see cref="EventArgs"/> instance containing the event data.</param>
        protected void btnAddComment_Click(object sender, EventArgs e)
        {
            CommentManager commentManager = new CommentManager();
            Comment comment = new Comment();
            int articleID = Convert.ToInt32(Request.QueryString["article"]);

            try
            {
                comment.CommentData = this.txtComment.Text.Trim();
                comment.UserID = applicationUser.UserID;
                comment.ArticleID = articleID;
                comment.IsActive = true;
                bool success = commentManager.UpdateComment(comment);
                if (success)
                {

                    this.pageActionMessage.InnerText = "Comment was added succesfully.";
                    this.pageActionMessage.Attributes.Add("class", "success-msg");

                    LoadPage();
                }
                else
                {
                    this.pageActionMessage.InnerText = "Failed to add comment.";
                    this.pageActionMessage.Attributes.Add("class", "error-msg");
                }
            }
            catch (Exception)
            {
                this.pageActionMessage.InnerText = "Failed to add comment.";
                this.pageActionMessage.Attributes.Add("class", "error-msg");
            }
            finally
            {
                commentManager = null;
                comment = null;
                this.txtComment.Text = "";
            }
        }
        #endregion

        #region [Private Methods]
        /// <summary>
        /// Loads the page
        /// </summary>
        private void LoadPage()
        {
            if (Request.QueryString["article"] != null)
            {
                Counter = 0;
                int articleID = Convert.ToInt32(Request.QueryString["article"]);
                ArticleManager articleManager = new ArticleManager();
                List<Article> articles = null;
                try
                {
                    articles = articleManager.GetArticles(articleID);
                    if (articles != null && articles.Count > 0)
                    {

                        this.articleRating.BehaviorID = articles[0].ArticleID + "," + applicationUser.UserID;
                        if (articles[0].IsActive != false)
                        {
                            this.lblArticleName.Text = articles[0].ArticleName;
                            this.lblLastUpdatedDate.Text = articles[0].LastUpdatedDate.ToString();
                            FillArticleImage(articles[0]);
                            FillArticleRating(articles[0]);
                            if (applicationUser.EmailAddress != AppConfiguration.AnonymousUserName)
                            {
                                if (articles[0].UserID != applicationUser.UserID)
                                {
                                    this.articleRating.ReadOnly = false;
                                    this.commentArea.Visible = true;
                                }
                                else
                                {
                                    this.articleRating.ReadOnly = true;
                                    this.commentArea.Visible = true;
                                }
                            }
                            else
                            {
                                this.articleRating.ReadOnly = true;
                            }
                            FillSteps(articles[0]);
                            FillArticleUser(articles[0]);
                            FillArticleTags(articles[0]);
                            FillArticleComments(articles[0].ArticleID);
                            FillVehicleModelDetails(articles[0]);

                        }
                        else
                        {
                            this.pageActionMessage.InnerText = "The article has been deleted by the user.";
                            this.pageActionMessage.Attributes.Add("class", "information-msg");
                        }
                    }
                    else
                    {
                        this.pageActionMessage.InnerText = "Failed to load the information";
                        this.pageActionMessage.Attributes.Add("class", "error-msg");
                    }


                }
                catch (Exception)
                {
                    this.pageActionMessage.InnerText = "Failed to load the information";
                    this.pageActionMessage.Attributes.Add("class", "error-msg");
                }
                finally
                {
                    articleManager = null;
                    articles = null;
                }
            }
        }
        /// <summary>
        /// Fills the article comment information
        /// </summary>
        /// <param name="article">article</param>
        private void FillArticleComments(int articleID)
        {
            CommentManager commentManager = new CommentManager();
            List<GetCommentByArticleID> articleComments = null;
            try
            {
                articleComments = commentManager.GetCommentByArticleID(articleID);
                if (articleComments != null && articleComments.Count > 0)
                {
                    this.rptrComments.DataSource = articleComments;
                    this.rptrComments.DataBind();
                }
            }
            catch (Exception)
            {
            }
            finally
            {
                commentManager = null;
                articleComments = null;
            }
        }
        /// <summary>
        /// Fills the article tag information
        /// </summary>
        /// <param name="article">article</param>
        private void FillArticleTags(Article article)
        {
            ArticleTagManager articleTagManager = new ArticleTagManager();
            List<GetTagByArticleID> articleTags = null;
            try
            {
                articleTags = articleTagManager.GetTagByArticleID(article.ArticleID);
                if (articleTags != null && articleTags.Count > 0)
                {
                    this.dtlTags.DataSource = articleTags;
                    this.dtlTags.DataBind();
                }
            }
            catch (Exception)
            {
            }
            finally
            {
                articleTagManager = null;
                articleTags = null;
            }
        }
        /// <summary>
        /// Fills the vehicle model information
        /// </summary>
        /// <param name="article">article</param>
        private void FillVehicleModelDetails(Article article)
        {
            VehicleModelManager vehicleModelManager = new VehicleModelManager();
            List<GetVehicleModelDetailsByArticleID> vehicleModelDetails =null;
            try
            {
                vehicleModelDetails = vehicleModelManager.GetVehicleModelsByArticleID(article.ArticleID);
                if (vehicleModelDetails != null && vehicleModelDetails.Count > 0)
                {
                    this.lblModelAndType.Text = vehicleModelDetails[0].VehicleModelName + " " + vehicleModelDetails[0].VehicleModelTypeName;
                    if (vehicleModelDetails[0].VehicleModelTypeImageURL != string.Empty)
                    {
                        StringBuilder pathToFile = new StringBuilder();
                        pathToFile.Append(AppConfiguration.VehicleImagePath);
                        pathToFile.Append(vehicleModelDetails[0].VehicleModelTypeImageURL.Substring(0, vehicleModelDetails[0].VehicleModelTypeImageURL.IndexOf(".")));
                        pathToFile.Append("/");
                        pathToFile.Append(vehicleModelDetails[0].VehicleModelTypeImageURL);


                        this.imgModelImage.ImageUrl = pathToFile.ToString();
                        pathToFile = null;
                    }
                    else
                    {
                        this.imgModelImage.ImageUrl = "images/imgNoModelImage.png";
                    }
                    this.lblYear.Text = vehicleModelDetails[0].VehicleYear.ToString() ;
                }
            }
            catch (Exception)
            {

                throw;
            }
            finally
            {
                vehicleModelManager = null;
                vehicleModelDetails = null;
            }
        }
        /// <summary>
        /// Fills the article user information
        /// </summary>
        /// <param name="article">article</param>
        private void FillArticleUser(Article article)
        {
            UserManager userManager = new UserManager();
            List<GetUserByArticleID> userDetails = null;
            try
            {
                userDetails = userManager.GetUserByArticleID(article.ArticleID);
                if (userDetails != null && userDetails.Count > 0)
                {
                    this.lnkWrittebBy.Text = userDetails[0].UserName;
                    if (userDetails[0].ProfilePictureURL == string.Empty)
                    {
                        this.imgUser.ImageUrl = "images/imgDefaultProfile.png";
                    }
                    else
                    {
                        this.imgUser.ImageUrl = AppConfiguration.UserProfileImagePath + userDetails[0].ProfilePictureURL;
                    }

                }
            }
            catch (Exception)
            {
            }
            finally
            {
                userManager = null;
                userDetails = null;
            }
        }
        /// <summary>
        /// Fills the article image
        /// </summary>
        /// <param name="article">the article</param>
        private void FillArticleImage(Article article)
        {
            if (article.ArticleImageUrl != string.Empty)
            {
                StringBuilder pathToFile = new StringBuilder();
                pathToFile.Append(AppConfiguration.ArticlePath);
                pathToFile.Append("/");
                pathToFile.Append(article.ArticleID);
                pathToFile.Append("/");
                pathToFile.Append(article.ArticleImageUrl);
                this.imgArticleImage.ImageUrl = pathToFile.ToString();
                pathToFile = null;
            }
            else
            {
                this.imgArticleImage.ImageUrl = "images/imgNoArticleImage.jpg";

            }
        }
        /// <summary>
        /// Fills the article rating
        /// </summary>
        /// <param name="article">articlesByVehicleDetail</param>
        private void FillArticleRating(Article article)
        {
            RatingManager articleRatingManager = new RatingManager();
            List<GetArticleRatingByArticleID> articleRatings = null;
            try
            {
                articleRatings = articleRatingManager.GetArticleRatingByArticleID(article.ArticleID);
                if (articleRatings != null && articleRatings.Count > 0)
                {
                    this.articleRating.CurrentRating = articleRatings[0].Rating;

                }
            }
            catch (Exception)
            {
            }
            finally
            {
                articleRatingManager = null;
                articleRatings = null;
            }
        }
        /// <summary>
        /// Fills the step information
        /// </summary>
        /// <param name="article">article</param>
        private void FillSteps(Article article)
        {
            StepManager stepManager = new StepManager();
            List<GetStepsUserOrArticle> stepDetails = null;
            try
            {
                stepDetails = stepManager.GetStepsByArticleID(article.ArticleID);
                if (stepDetails != null && stepDetails.Count > 0)
                {
                    this.lstSteps.DataSource = stepDetails;
                    this.lstSteps.DataBind();
                    this.rptrGoToLinks.DataSource = stepDetails;
                    this.rptrGoToLinks.DataBind();

                }

            }
            catch (Exception)
            {
            }
            finally
            {
                stepManager = null;
                stepDetails = null;
            }
        }

        /// <summary>
        /// Reads the loaded  data
        /// </summary>
        /// <param name="stepURL">the step url</param>
        /// <returns>the lines in the text</returns>
        private string LoadStepData(string stepURL)
        {

            string lines = System.IO.File.ReadAllText(stepURL);
            return lines;

        }
        #endregion      

    }
}